#include "GroupItemList.h"

GroupItemList::GroupItemList(std::list< std::pair<std::string,std::string>* >* keyValueList, int posX, int posY, int width, int height, Widget *parent)
		:ItemList(posX, posY, parent){
	this->pos = 0;
	this->cantItems = 0;
	this->keySelected = "";

	this->parcel->width = width;
	this->parcel->height = height;

	this->surface =	SurfaceUtils::colorSurface(width,height,Color::BLANCO);

	this->listKeyValue = keyValueList;
	this->cantItems = keyValueList->size();
	this->keySelected = keyValueList->front()->first;
	fillButtonList();
}

GroupItemList::~GroupItemList() {
	while(!listKeyValue->empty()){
		delete listKeyValue->back();
		listKeyValue->pop_back();
	}

	delete listKeyValue;

}

void GroupItemList::handleEvent(Event event) {

	if (!isMouseOver(event))
		return;

	if ((event.getType()) == MouseButtonPressed) {
		std::list<ButtonListItem*>::iterator it;
		for (it = buttonList.begin(); it != buttonList.end(); ++it) {
			if(((ButtonListItem*)*it)->isMouseOver(event,parcel)){
				std::list<ButtonListItem*>::iterator it2;
				for (it2 = buttonList.begin(); it2 != buttonList.end(); ++it2) {
					if(((ButtonListItem*)*it2)->isMouseOver(event,parcel)){
						((ButtonListItem*)*it2)->setPressed(true);
						this->keySelected= ((ButtonListItem*)*it2)->getKeyValue();
					}else{
						((ButtonListItem*)*it2)->setPressed(false);
					}
				}
			}
		}
		Logger::log("GroupItemList", "handleEvent", "MOUSEBUTTONDOWN");
	} else if ((event.getType()) == MouseButtonReleased) {
		Logger::log("GroupItemList", "handleEvent", "SDL_MOUSEBUTTONUP");
	}
	Widget::handleEvent(event);
}

void GroupItemList::resolve() {
	std::list<ButtonListItem*>::iterator it;
	for (it = buttonList.begin(); it != buttonList.end(); ++it) {
		((ButtonListItem*)*it)->resolve();
	}
	Widget::resolve();
}

void GroupItemList::showOn(SDL_Surface* surface) {
	//Dibujo botones visibles en la lista
	std::list<ButtonListItem*>::iterator it;
	for (it = buttonList.begin(); it != buttonList.end(); ++it) {
		((ButtonListItem*)*it)->showOn(this->surface);
	}

	Widget::showOn(surface);
}

void GroupItemList::fillButtonList(){
	std::list< std::pair<std::string,std::string>* >::iterator it;
	int tmpPos = 0;
	int tmpX = 0;
	int tmpY = 0;

	bool flagSelected = false;
	it = listKeyValue->begin();
	while ( it != listKeyValue->end()) {
		if(tmpPos>=pos){
			std::string path = (*it)->second;
			if((*it)->first == keySelected)
				flagSelected = true;
			else
				flagSelected = false;
			ButtonListItem* tmpButton = new ButtonListItem((*it)->first,path,flagSelected,tmpX, tmpY, this);
			buttonList.push_back(tmpButton);
			tmpX = tmpX + DEFAULT_BUTTON_WIDTH + DEFAULT_PADDING;
		}
		tmpPos++;
		it++;
	}
}

std::string GroupItemList::getSelected(){
	return keySelected;
}

